const OrderDao = require('../database/OrderDao');
const AgriDao = require('../database/AgriDao');
const ArticleDao = require('../database/ArticleDao');
const UserDao = require('../database/UserDao');

class OrderController {
  constructor(pool) {
    this.orderDao = new OrderDao(pool);
    this.agriDao = new AgriDao(pool);
    this.articleDao = new ArticleDao(pool);
    this.userDao = new UserDao(pool);

      // 确保方法绑定到当前实例
  this.createOrderHandler = this.createOrderHandler.bind(this);
  this.addPurchaseOrder = this.addPurchaseOrder.bind(this);
  this.addSupplyOrder = this.addSupplyOrder.bind(this);
  }

  // 获取用户订单（区分出售/收购）
  async getUserOrders(req, res) {
    const { userId } = req.user; // 获取 userId
    try {
      const [buyOrders, sellOrders] = await Promise.all([
        this.orderDao.getOrdersByBuyer(userId), // 收购订单
        this.orderDao.getOrdersBySeller(userId) // 出售订单
      ]);

      const orders = [
        ...buyOrders.map(order => ({ ...order, type: '收购' })), // 我是买家
        ...sellOrders.map(order => ({ ...order, type: '出售' })) // 我是卖家
      ];

      res.json({ code: 200, msg: '获取成功', data: orders });
    } catch (error) {
      console.error('获取订单失败:', error);
      res.status(500).json({ code: 500, msg: '获取订单失败' });
    }
  }

  // 创建订单（通用方法）
  async createOrderHandler(req, res, isPurchase) {
    const { userId } = req.user; // 获取 userId
    const { counterpart_id, items } = req.body;
    const role = isPurchase ? '买家' : '卖家';

    try {


      const orderItems = [];
      for (const item of items) {
        const { product_id, quantity, remarks, product_type } = item;

        if (!product_id || !quantity || !product_type) {
          return res.status(400).json({ code: 400, msg: '订单项缺少必要字段' });
        }

        // 检查库存/剩余数量
        if (isPurchase) {
          const stock = await this.agriDao.getProductStock(product_id);
          if (stock < quantity) {
            return res.status(400).json({ code: 400, msg: '库存不足' });
          }
          await this.agriDao.reduceStock(product_id, quantity);
        } else {
          const remaining = await this.articleDao.getRemainingQuantity(product_id);
          if (remaining < quantity) {
            return res.status(400).json({ code: 400, msg: '收购公告剩余数量不足' });
          }
          await this.articleDao.reduceRemainingQuantity(product_id, quantity);
        }

        orderItems.push({ product_id, quantity, remarks, product_type });
      }

      // 创建订单
      const createdOrder = await this.orderDao.createOrder({
        buyer_id: isPurchase ? userId : counterpart_id,
        seller_id: isPurchase ? counterpart_id : userId,
        items: orderItems
      });

      res.json({ code: 200, msg: '操作成功', data: createdOrder });

    } catch (error) {
      console.error(`${role}创建订单失败:`, error);
      res.status(500).json({ code: 500, msg: `${role}创建订单失败` });
    }
  }

  // 购买农产品订单（经销商/政府 -> 农户）
  async addPurchaseOrder(req, res) {
    req.body.counterpart_id = req.body.seller_id; // 统一格式
    return this.createOrderHandler(req, res, true);
  }

  // 响应收购公告订单（农户 -> 经销商/政府）
  async addSupplyOrder(req, res) {
    req.body.counterpart_id = req.body.buyer_id; // 统一格式
    return this.createOrderHandler(req, res, false);
  }
}

module.exports =  OrderController;
